package at.sysarch.filter;

import java.awt.image.RenderedImage;
import java.awt.image.renderable.ParameterBlock;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.media.jai.RenderedOp;
import at.sysarch.utils.ImageChangedEvent;
import at.sysarch.utils.ImageChangedListener;

public class ThresholdFilter extends AbstractListenerManager implements ImageChangedListener {

	PlanarImage _image = null;

	private int _lowThreshold = 255;
	private int _highThreshold = 255;
	private int _mapThreshold = 255;

	public void setInputImage(PlanarImage image) {
		_image = image;
		updateImage();
	}

	@Override
	public void imageChanged(ImageChangedEvent event) {
		setInputImage(event.getImage());
	}

	private void updateImage() {
		if (_image != null) {
			RenderedOp image = threshold(_image, _lowThreshold, _highThreshold, _mapThreshold);
			fireImageChanged(image);
		}
	}

	private RenderedOp threshold(RenderedImage image, int lowThreshold, int highThreshold, int mapThreshold) {
		double[] low, high, map;
		int bands = 3;
		low = new double[bands];
		high = new double[bands];
		map = new double[bands];
		for (int i = 0; i < bands; i++) {
			low[i] = lowThreshold;
			high[i] = highThreshold;
			map[i] = mapThreshold;
		}
		ParameterBlock pb = new ParameterBlock();
		pb.addSource(image);
		pb.add(low);
		pb.add(high);
		pb.add(map);
		return JAI.create("threshold", pb);
	}

	public int getLowThreshold() {
		return _lowThreshold;
	}

	public void setLowThreshold(int lowThreshold) {
		System.out.println("lowThreshold set: " + lowThreshold);
		_lowThreshold = lowThreshold;
		updateImage();
	}

	public int getHighThreshold() {
		return _highThreshold;
	}

	public void setHighThreshold(int highThreshold) {
		_highThreshold = highThreshold;
		updateImage();
	}

	public int getMapThreshold() {
		return _mapThreshold;
	}

	public void setMapThreshold(int mapThreshold) {
		_mapThreshold = mapThreshold;
		updateImage();
	}

}
